// pages/auth/login_page.dart
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:go_router/go_router.dart';

import '../../bloc/auth/auth_bloc.dart';
import '../../bloc/auth/auth_event.dart';
import '../../bloc/auth/auth_state.dart';
import '../../generated/assets.dart';



class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();

  // 控制验证码按钮是否可点击
  final _isButtonEnabled = ValueNotifier<bool>(false);
  // 控制倒计时
  final _countdownNotifier = ValueNotifier<int>(0);
  // 倒计时定时器
  Timer? _countdownTimer;



  @override
  void initState() {
    super.initState();
    // 监听手机号输入变化
    _phoneController.addListener(_checkPhoneLength);
  }

  // 检查手机号长度，控制按钮状态
  void _checkPhoneLength() {
    final phone = _phoneController.text;
    // 确保手机号是11位数字
    final isPhoneValid = phone.length == 11 && RegExp(r'^\d{11}$').hasMatch(phone);
    _isButtonEnabled.value = isPhoneValid && _countdownNotifier.value == 0;
  }



  // 开始倒计时
  void _startCountdown() {
    _countdownNotifier.value = 60;
    _isButtonEnabled.value = false;

    _countdownTimer?.cancel();
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdownNotifier.value > 0) {
        _countdownNotifier.value -= 1;
      } else {
        _countdownTimer?.cancel();
        _checkPhoneLength(); // 倒计时结束后，重新检查手机号是否有效
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: BlocListener<AuthBloc, AuthState>(
        listener: (context, state) {
          if (state is AuthLoading) {
            // LoadingDialog.show(context);
            EasyLoading.show(status: 'loading');
          } else {
            // LoadingDialog.hide(context);
            EasyLoading.dismiss();
          }

          if (state   is AuthFailure) {
             EasyLoading.showToast(state.error);
          }
          if (state is AuthCode) {
            EasyLoading.showToast(state.message);
            // 开始倒计时
            _startCountdown();
          }else if (state is AuthAuthenticated) {
              context.go('/mainhome');
          }

          if (state is AuthFailure) {
            // ScaffoldMessenger.of(context)
            //   ..hideCurrentSnackBar()
            //   ..showSnackBar(
            //     SnackBar(content: Text('登录失败: ${state.error}')),
            //   );
          }
        },
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                SizedBox(height: MediaQuery.of(context).size.height * 0.2),
                // Logo
                // Icon(Icons.ac_unit, color: Color(0xFF4DD0E1), size: 100), // Placeholder for your logo
                Image.asset(
                  Assets.assetsLogo, // Make sure this path is correct
                  width: 137, // Adjust size as needed
                  height: 137,
                  // color: accentColor, // Apply the accent color to the monochrome image
                ),
                const SizedBox(height: 60),
                Text('手机号', textAlign: TextAlign.left, style: TextStyle(
                  // 使用你需要的颜色值 (例如 Color(0xFF4DD0E1)
                  fontSize: 14,
                  color: Color(0xFF000000),
                ),),
                const SizedBox(height: 8),
                // 手机号输入框
                TextField(
                  controller: _phoneController,
                  keyboardType: TextInputType.phone,
                  maxLength: 11,
                  inputFormatters: [
                    FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
                    LengthLimitingTextInputFormatter(11), // 限制长度为11
                  ],
                  style: const TextStyle(
                    color: Colors.black, // 输入文字颜色为白色
                    fontSize: 14,
                  ),
                  decoration: const InputDecoration(
                    hintText: '请输入手机号码',
                    hintStyle: TextStyle(
                      color: Color(0xFF808080), // 占位符文字颜色为红色
                      fontSize: 14,
                    ),
                    counterText: '', // 隐藏右下角字数统计
                    // 或者无边框样式
                    border: InputBorder.none,
                  ),
                ),

                Container(
                  height: 1,
                  color: Color(0xFFCDCCCC),
                ),

                const SizedBox(height: 26),
                // 验证码输入框

                Text('验证码', textAlign: TextAlign.left, style: TextStyle(
                  // 使用你需要的颜色值 (例如 Color(0xFF4DD0E1)
                  fontSize: 14,
                  color: Color(0xFF000000),
                ),),

                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _codeController,
                        keyboardType: TextInputType.number,
                        maxLength: 4,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
                          LengthLimitingTextInputFormatter(4), // 限制长度为11
                        ],
                        style: const TextStyle(
                          color: Colors.black, // 输入文字颜色为白色
                          fontSize: 14,
                        ),
                        decoration: const InputDecoration(
                          hintText: '请输入验证码',
                          hintStyle: TextStyle(
                            color: Color(0xFF808080), // 占位符文字颜色为红色
                            fontSize: 14,
                          ),
                          counterText: '', // 隐藏右下角字数统计
                          // 或者无边框样式
                          border: InputBorder.none,
                        ),
                      ),
                    ),

                    const SizedBox(width: 10),

                    ValueListenableBuilder<bool>(
                      valueListenable: _isButtonEnabled,
                      builder: (context, isEnabled, child) {
                        return ElevatedButton(
                          onPressed: isEnabled
                              ? () {
                            // 点击获取验证码
                            context.read<AuthBloc>().add(
                              GetCodePressed(
                                  phone: _phoneController.text
                              ),
                            );

                          }
                              : null, // 不可点击时为null
                          style: ElevatedButton.styleFrom(
                            backgroundColor: isEnabled
                                ? const Color(0xFF4DD0E1) // 可点击时的颜色
                                : Colors.grey, // 不可点击时的颜色
                            foregroundColor: Colors.white,
                          ),
                          child: ValueListenableBuilder<int>(
                            valueListenable: _countdownNotifier,
                            builder: (context, count, child) {
                              return Text(count > 0
                                  ? '${count}S'
                                  : '获取验证码',style: TextStyle(
                                    fontSize: 14,
                              ),
                              );
                            },
                          ),
                        );
                      },
                    )




                  ],
                ),

                Container(
                  height: 1,
                  color: Color(0xFFCDCCCC),
                ),

                const SizedBox(height: 40),
                // 登录按钮
                ElevatedButton(
                  onPressed: () {
                    context.read<AuthBloc>().add(
                      LoginButtonPressed(
                        phone: _phoneController.text,
                        code: _codeController.text,
                      ),
                    );
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF4DD0E1),
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(26),
                    ),
                  ),
                  child: const Text(
                    '登录',
                    style: TextStyle(fontSize: 14, color: Colors.white),
                  ),
                ),
                const SizedBox(height: 20),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    _countdownTimer?.cancel(); // 取消定时器
    _isButtonEnabled.dispose();
    _countdownNotifier.dispose();
    super.dispose();
  }
}
